#include <Starter.hpp>

Starter::Starter(){

	userInterface = 0;
	serverInformation = 0;

	signalHandler = 0;
	signalMask = 0;

	connectionManager = 0;
	ibrcNetworkManager = 0;

}


int Starter::start() {

	/*
	 * UI
	 */
	userInterface = new UserInterface();

	/*
	 * Init SignalHandler
	 */
	signalHandler = SignalHandler::instance();
	signalHandler->registerSignal(SIGTERM);
	signalHandler->registerSignal(SIGINT);
	signalMask = (1 << SIGTERM) | (1 << SIGINT);

	/* Create manager for local TCP/IP Connections */
	connectionManager = new ConnectionManager (userInterface);
	/* Create manager for network data */
	ibrcNetworkManager = new IBRCNetworkManager(connectionManager);
	/* Create helper for exporting of server information */
	serverInformation = new ServerInformation (ibrcNetworkManager, connectionManager);

	/* Warm up */
	connectionManager->init();
	ibrcNetworkManager->processData();

	/* main-loop */
	while (ibrcNetworkManager->getState() == IBRCNetworkManager::STATE_RUNNING) {

		/* Receive data from TCP/IP connections */
		connectionManager->handleInputData();

		/* Check if we received signals */
		handleSignals();


		while(connectionManager->isMessagesAvailable()){
			/* Process received messages */
			ibrcNetworkManager->processData();

			/* Transmit data to local TCP/IP connections */
			connectionManager->handleOutputData();

		}


		/* Export current server details to file */
		serverInformation->writeServerInformationFile();

	}

	connectionManager->closeAllConnections();

	serverInformation->writeShutdownNote();

	return 0;
}


void Starter::handleSignals(){

	switch (signalHandler->getSignalState(signalMask)) {

	case (1 << SIGTERM):
	case (1 << SIGINT):

		std::cout << Config::instance()->getClientName() << " Received signal to quit" << std::endl;

		ClientMessagePackage *clientMessagePackage = new ClientMessagePackage(userInterface);
		clientMessagePackage->setMessageType(ClientMessagePackage::TYPE_QUIT_MESSAGE);

		connectionManager->pushInboundMessagePackageList(clientMessagePackage);

		break;

	}

}
